﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using AxWMPLib;
using System.IO;
using System.Data.SqlClient;


namespace MusicPlayer
{
    public partial class Form1 : Form
    {
        #region 定义
        private bool Is_login = false;
        private List<SongsInfo> localSongsList = new List<SongsInfo>(); //本地音乐List
        private List<SongsInfo> favoriteSongsList = new List<SongsInfo>();  //收藏音乐List
        SongsInfo currPlaySong = new SongsInfo(null); //用于存储当前播放歌曲的信息
        SongsInfo currSelectedSong = new SongsInfo(null);       //用于查看详情

        //关于随机播放的定义
        public enum PlayMode { Shuffle = 0, SingleLoop, ListLoop };  //播放模式枚举
        public PlayMode currPlayMode = PlayMode.ListLoop;  //设置默认播放模式为列表播放
        private int[] randomList;           //随机播放序列
        private int randomListIndex = 0;    //序列索引
        private int jumpSongIndex;          //手动选中的歌曲需要在随机过程中跳过

        //保存路径的定义
        private string localSongsFilePath = Application.StartupPath + "\\songListHistory.txt"; //本地音乐历史记录存储位置
        private string favoriteSongsFilePath = Application.StartupPath + "\\favoriteSongsHistory.txt"; //收藏音乐存储位置
        #endregion

        #region 窗体加载
        public Form1()
        {
            InitializeComponent();
            lbMenu.Items.Add("本地音乐");
            lbMenu.Items.Add("我的收藏");
            lbMenu.Items.Add("用户");
        }
        private void Form1_Load(object sender, EventArgs e) //每当用户加载窗体时发生
        {
            //重置播放器状态信息
            ReloadStatus();
            //读取播放器列表历史记录
            localSongsList = ReadHistorySongsList(localSongsFilePath);
            favoriteSongsList = ReadHistorySongsList(favoriteSongsFilePath);
            //设置专辑图片控件到顶部页面（z-index)
            //pbAlbumImage.BringToFront();
            pbAlbumImage.BringToFront();
        }
        #endregion

        #region 添加音乐
        //添加音乐
        private void Addmusic_Click(object sender, EventArgs e)
        {
            //实例化一个打开文件的对话框
            OpenFileDialog of = new OpenFileDialog();

            //文件对话框初始路径
            of.InitialDirectory = @"E:\CloudMusic";

            //可以让选择器同时选择多个文件
            of.Multiselect = true; 

            of.Title = "请选择音乐文件";
            //指定选择文件的类型
            of.Filter = "媒体文件|*.mp3;*.wav;*.wma;*.avi;*.mpg;*.asf;*.wmv";

            if(of.ShowDialog() == DialogResult.OK)
            {
                //把用户选择的文件存储到本地音乐List中
                for(int i=0; i<of.FileNames.Length; i++)
                {
                    string path = of.FileNames[i];
                    if (!IsExistInList(path))
                        localSongsList.Add(new SongsInfo(path));
                }
                AddSongsToListView(localSongsList);
                //保存路径到本地
                SaveSongsListHistory(localSongsFilePath, localSongsList);
            }
        }
        //判断本地音乐列表中是否已经包含选中的歌曲
        private bool IsExistInList(string path)
        {
            for (int i = 0; i < localSongsList.Count; i++)
            {
                if (path == localSongsList[i].FilePath)
                    return true;
            }
            return false;
        }
        //把选中的音乐加到ListView中
        private void AddSongsToListView(List<SongsInfo> songList)
        {
            //lvSongList.BeginUpdate()和lvSongList.EndUpdate()是为了解决闪烁问题
            lvSongList.BeginUpdate();
            lvSongList.Items.Clear();
            foreach(SongsInfo song in songList)
            {
                string[] songAry = new string[7];
                int currCount = lvSongList.Items.Count + 1;
                if(currCount < 10)
                    songAry[0] = "0" + currCount;
                else
                    songAry[0] = "" + currCount;
                songAry[1] = song.OriginName;
                songAry[2] = song.Artist;
                songAry[3] = song.Album;
                songAry[4] = song.Duration;
                songAry[5] = song.Filesize;
                songAry[6] = song.FilePath;

                ListViewItem lvItem = new ListViewItem(songAry);
                lvSongList.Items.Add(lvItem);
            }
            lvSongList.EndUpdate();
        }
        #endregion

        #region 播放列表双击事件
        private void lvSongList_DoubleClick(object sender, EventArgs e)
        {
            int currIndex = lvSongList.SelectedItems[0].Index;
            string songFilePath = lvSongList.Items[currIndex].SubItems[6].Text;
            if(currPlaySong.FilePath == songFilePath)
            {
                //选中歌曲为正在播放的歌曲
                if(AxWmp.playState.ToString() == "wmppsPlaying")
                {
                    AxWmp.Ctlcontrols.pause();
                    picPlay.Image = MusicPlayer.Properties.Resources.play;
                }
                else if (AxWmp.playState.ToString() == "wmppsPaused")
                {
                    AxWmp.Ctlcontrols.play();
                    picPlay.Image = MusicPlayer.Properties.Resources.pause;
                }
            }
            else
            {
                //选中的为其他歌曲
                BuildRandomList(lvSongList.Items.Count);
                jumpSongIndex = currIndex;
                currPlaySong = new SongsInfo(songFilePath);
                AxWmp.URL = songFilePath;
                AxWmp.Ctlcontrols.play();
                picPlay.Image = MusicPlayer.Properties.Resources.pause;
            }
            lvSongList.Items[currIndex].Focused = true;
        }
        #endregion

        #region 鼠标移入和移出事件集合
        //鼠标移入和移出事件集合
        private void picClose_MouseEnter(object sender, EventArgs e)
        {
            picClose.Image = MusicPlayer.Properties.Resources.close2;
        }
        private void picClose_MouseLeave(object sender, EventArgs e)
        {
            picClose.Image = MusicPlayer.Properties.Resources.close;
        }
        private void picBig_MouseEnter(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
                picBig.Image = MusicPlayer.Properties.Resources.big2;
            else if (this.WindowState == FormWindowState.Maximized)
                picBig.Image = MusicPlayer.Properties.Resources.windowed2;
        }
        private void picBig_MouseLeave(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
                picBig.Image = MusicPlayer.Properties.Resources.big;
            else if (this.WindowState == FormWindowState.Maximized)
                picBig.Image = MusicPlayer.Properties.Resources.windowed;
        }
        private void picSmall_MouseEnter(object sender, EventArgs e)
        {
            picSmall.Image = MusicPlayer.Properties.Resources.small2;
        }
        private void picSmall_MouseLeave(object sender, EventArgs e)
        {
            picSmall.Image = MusicPlayer.Properties.Resources.small;
        }
        private void Addmusic_MouseEnter(object sender, EventArgs e)
        {
            Addmusic.Image = MusicPlayer.Properties.Resources.add2;
        }
        private void Addmusic_MouseLeave(object sender, EventArgs e)
        {
            Addmusic.Image = MusicPlayer.Properties.Resources.add;
        }
        private void picBack_MouseEnter(object sender, EventArgs e)
        {
            picBack.Image = MusicPlayer.Properties.Resources.back2;
        }
        private void picBack_MouseLeave(object sender, EventArgs e)
        {
            picBack.Image = MusicPlayer.Properties.Resources.back;
        }
        private void picPlay_MouseEnter(object sender, EventArgs e)
        {
            if(AxWmp.playState.ToString() == "wmppsPlaying")
                picPlay.Image = MusicPlayer.Properties.Resources.pause2;
            else 
                picPlay.Image = MusicPlayer.Properties.Resources.play2;
        }
        private void picPlay_MouseLeave(object sender, EventArgs e)
        {
            if (AxWmp.playState.ToString() == "wmppsPlaying")
                picPlay.Image = MusicPlayer.Properties.Resources.pause;
            else 
                picPlay.Image = MusicPlayer.Properties.Resources.play;
        }
        private void picNext_MouseEnter(object sender, EventArgs e)
        {
            picNext.Image = MusicPlayer.Properties.Resources.next2;
        }
        private void picNext_MouseLeave(object sender, EventArgs e)
        {
            picNext.Image = MusicPlayer.Properties.Resources.next;
        }
        private void picMode_MouseEnter(object sender, EventArgs e)
        {
            if (currPlayMode == PlayMode.ListLoop)
                picMode.Image = MusicPlayer.Properties.Resources.cycle2;
            else if (currPlayMode == PlayMode.Shuffle)
                picMode.Image = MusicPlayer.Properties.Resources.random2;
            else
                picMode.Image = MusicPlayer.Properties.Resources.single2;
        }
        private void picMode_MouseLeave(object sender, EventArgs e)
        {
            if (currPlayMode == PlayMode.ListLoop)
                picMode.Image = MusicPlayer.Properties.Resources.cycle;
            else if (currPlayMode == PlayMode.Shuffle)
                picMode.Image = MusicPlayer.Properties.Resources.random;
            else
                picMode.Image = MusicPlayer.Properties.Resources.single;
        }
        private void tbVoi_ValueChanged(object sender, EventArgs e)
        {
            AxWmp.settings.volume = tbVoi.Value;
        }
        private void picSmallAlbumImage_MouseEnter(object sender, EventArgs e)
        {
            picSmallAlbumImage.Image = MusicPlayer.Properties.Resources.unfold;
        }
        private void picSmallAlbumImage_MouseLeave(object sender, EventArgs e)
        {
            picSmallAlbumImage.Image = null;
        }
        #endregion

        #region 播放等按钮
        //播放函数，由上一首和下一首调用
        private void Play(int index)
        {
            //设置被播放音乐项的状态
            lvSongList.Items[index].Focused = true;
            //如果你指定的项在可视区域以外，调用这个函数后列表视图控件会自动滚动到让你指定的项可见
            lvSongList.Items[index].EnsureVisible();
            lvSongList.Items[index].Selected = true;

            if (AxWmp.playState.ToString() == "wmppsPlaying") //播放->其他状态
            {
                AxWmp.Ctlcontrols.pause();
                picPlay.Image = MusicPlayer.Properties.Resources.play;
            }
            else if (AxWmp.playState.ToString() != "wmppsPaused")      //更改播放路径并播放
            {
                BuildRandomList(lvSongList.Items.Count);
                jumpSongIndex = index;
                currPlaySong = new SongsInfo(lvSongList.SelectedItems[0].SubItems[6].Text);
                AxWmp.URL = currPlaySong.FilePath;
                AxWmp.Ctlcontrols.play();
                picPlay.Image = MusicPlayer.Properties.Resources.pause;
            }
            else   //暂停->播放
            {
                AxWmp.Ctlcontrols.play();
                picPlay.Image = MusicPlayer.Properties.Resources.pause;
            }
        }
        //点击播放或暂停
        private void picPlay_Click(object sender, EventArgs e)
        {
            if (AxWmp.playState.ToString() == "wmppsPlaying")       //播放->暂停
            {
                AxWmp.Ctlcontrols.pause();
                picPlay.Image = MusicPlayer.Properties.Resources.play;
            }
            else if (AxWmp.playState.ToString() == "wmppsPaused")    //暂停->播放
            {
                AxWmp.Ctlcontrols.play();
                picPlay.Image = MusicPlayer.Properties.Resources.pause;
            }

        }
        //点击上一首
        private void picBack_Click(object sender, EventArgs e)
        {
            if (lvSongList.Items.Count == 0)
            {
                MessageBox.Show("请先添加曲目至目录");
                return;
            }
            int currIndex = lvSongList.SelectedItems[0].Index;
            if (currIndex > 0)
            {
                AxWmp.Ctlcontrols.stop();
                currIndex -= 1;
            }
            else
            {
                AxWmp.Ctlcontrols.stop();
                currIndex = lvSongList.Items.Count - 1;
            }
            Play(currIndex);
        }
        //点击下一首
        private void picNext_Click(object sender, EventArgs e)
        {
            if (lvSongList.Items.Count == 0)
            {
                MessageBox.Show("请先添加曲目至目录");
                return;
            }
            int currIndex = lvSongList.SelectedItems[0].Index;
            if (currIndex < lvSongList.Items.Count - 1)
            {
                AxWmp.Ctlcontrols.stop();
                currIndex += 1;
            }
            else
            {
                AxWmp.Ctlcontrols.stop();
                currIndex = 0;
            }
            Play(currIndex);
        }
        #endregion

        #region 窗口变化
        /*
         * 关闭、最大化、最小化按钮点击事件
         */
        private void picClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void picBig_Click(object sender, EventArgs e)
        {
            if(this.WindowState == FormWindowState.Normal)
            {
                picBig.Image = MusicPlayer.Properties.Resources.windowed;
                this.WindowState = FormWindowState.Maximized;
            }
            else if(this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
                picBig.Image = MusicPlayer.Properties.Resources.big;
            }
            
        }
        private void picSmall_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
        /*
         * 拖动窗口
         */
        Point downPoint;
        private void LogoName_MouseDown(object sender, MouseEventArgs e)
        {
            downPoint = new Point(e.X, e.Y);
        }
        private void LogoName_MouseMove(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - downPoint.X, this.Location.Y + e.Y - downPoint.Y);
            }
        }
        #endregion

        #region 定时器、进度条、音量
        //定时器
        private void timerPlay_Tick(object sender, EventArgs e)
        {
            //设置当前播放时间
            lbcurrTime.Text = AxWmp.Ctlcontrols.currentPositionString;
            lbEndTime.Text = currPlaySong.Duration.Remove(0, 3);

            //设置滑动条值
            tkbMove.Value = (int)AxWmp.Ctlcontrols.currentPosition;
        }
        //拖动进度条
        private void tkbMove_Scroll(object sender, EventArgs e)
        {
            AxWmp.Ctlcontrols.pause();
            AxWmp.Ctlcontrols.currentPosition = this.tkbMove.Value;
        }
        //停止拖动进度条
        private void tkbMove_MouseUp(object sender, MouseEventArgs e)
        {
            AxWmp.Ctlcontrols.play();
        }
        #endregion

        #region 播放器控件状态改变事件
        /*
         * 播放器控件状态改变事件
         */
        private void AxWmp_PlayStateChange(object sender, _WMPOCXEvents_PlayStateChangeEvent e)
        {
            switch (e.newState)
            {
                case 0:    // Stopped 未知状态
                    break;
                case 1:    // Stopped 停止
                    timerPlay.Stop();
                    ReloadStatus();
                    break;
                case 2:    // Paused 暂停
                    timerPlay.Stop();
                    break;
                case 3:   // Playing 正在播放
                    timerPlay.Start();
                    //显示专辑图片
                    pbAlbumImage.Image = currPlaySong.AlbumImage;
                    picSmallAlbumImage.BackgroundImage = currPlaySong.SmallAblum;
                    //显示歌曲标题名字和歌手名
                    lbSmallAlbumSongName.Text = currPlaySong.OriginName;
                    lbSmallAlbumSingerName.Text = currPlaySong.Artist;

                    //AxWmp.currentMedia.duration 获取文件的时间长度 
                    tkbMove.Maximum = (int)AxWmp.currentMedia.duration;
                    break;
                case 8:  //一首音乐播放结束
                    //获取音乐播放文件路径，并添加到播放控件
                    string path = GetPath();
                    // AxWmp.newMedia(path) 创建一个IWMPMedia的实例
                    WMPLib.IWMPMedia media = AxWmp.newMedia(path); 
                    AxWmp.currentPlaylist.appendItem(media);
                    break;
            }
        }
        /*
         * 重置播放器状态信息
         */
        private void ReloadStatus()
        {
            tkbMove.Value = 0;
            tbVoi.Maximum = 100;
            tbVoi.Value = tbVoi.Maximum / 2;
            //设置专辑封面为默认
            pbAlbumImage.Image = MusicPlayer.Properties.Resources.defaultBigAblum;

        }
        #endregion

        #region 播放模式
        //播放模式
        private string GetPath()
        {
            int currIndex = lvSongList.SelectedItems[0].Index;
            switch (currPlayMode)
            {
                case PlayMode.ListLoop:
                    if (currIndex != lvSongList.Items.Count - 1)
                        currIndex += 1;
                    else
                        currIndex = 0;
                    break;
                case PlayMode.SingleLoop:
                    break;
                case PlayMode.Shuffle:
                    //当局结束
                    if (randomListIndex > randomList.Length - 1)
                        startNewRound();

                    //匹配到需要跳过的歌曲
                    if(randomList[randomListIndex] == jumpSongIndex)
                        if (randomListIndex == randomList.Length - 1)   //当局结束
                            startNewRound();
                        else
                            randomListIndex++;
                    currIndex = randomList[randomListIndex++];
                    break;
            }
            lvSongList.Items[currIndex].Selected = true;//设定选中            
            lvSongList.Items[currIndex].EnsureVisible();//保证可见
            lvSongList.Items[currIndex].Focused = true;
            currPlaySong = new SongsInfo(lvSongList.SelectedItems[0].SubItems[6].Text);

            return currPlaySong.FilePath;

        }
        private void startNewRound()
        {
            //重新生成随机序列
            BuildRandomList(lvSongList.Items.Count);
            //第二轮开始 播放所有歌曲 不跳过
            jumpSongIndex = -1;
        }
        //生成随机序列
        private void BuildRandomList(int songListCount)
        {
            randomListIndex = 0;
            randomList = new int[songListCount];
            //初始化序列
            for (int i = 0; i < songListCount; i++)
                randomList[i] = i;
            //随机序列
            for (int i = songListCount - 1; i >= 0; i--)
            {
                Random r = new Random(Guid.NewGuid().GetHashCode());
                int j = r.Next(0, songListCount - 1);
                swap(randomList, i, j);
            }
        }
        private void swap(int[] arr, int a, int b)
        {
            int temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }
        private void picMode_Click(object sender, EventArgs e)
        {
            if (currPlayMode == PlayMode.ListLoop)
                currPlayMode = PlayMode.Shuffle;
            else
                currPlayMode += 1;
            if (currPlayMode == PlayMode.SingleLoop)
                picMode.Image = MusicPlayer.Properties.Resources.single2;
            else if (currPlayMode == PlayMode.ListLoop)
                picMode.Image = MusicPlayer.Properties.Resources.cycle2;
            else
                picMode.Image = MusicPlayer.Properties.Resources.random2;
        }

        #endregion

        #region 读写播放列表历史记录
        //保存历史记录到本地文件
        private void SaveSongsListHistory(string savePath, List<SongsInfo> songsList)
        {
            string saveString = "";
            for (int i = 0; i < songsList.Count; i++)
            {
                saveString += songsList[i].FilePath + "};{";
            }
            File.WriteAllText(savePath, saveString);
        }
        //读取历史记录到本地音乐
        private List<SongsInfo> ReadHistorySongsList(string filePath)
        {
            List<SongsInfo> resSongList = new List<SongsInfo>();
            string readString = "";
            if (File.Exists(filePath))
            {
                readString = File.ReadAllText(filePath);
                if (readString != "")
                {
                    string[] arr = readString.Split(new string[] { "};{" }, StringSplitOptions.None);
                    foreach (string path in arr)
                    {
                        if (path != null && path != "" && File.Exists(path))
                        {
                            resSongList.Add(new SongsInfo(path));
                        }
                    }
                }
            }
            else
                File.Create(filePath);
            return resSongList;
        }

        #endregion

        #region 窗体左部菜单
        //菜单按钮选中事件
        private void lbMenu_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (lbMenu.SelectedIndex)
            {
                case 0:     //选中的是本地列表
                    lvSongList.Items.Clear();
                    AddSongsToListView(localSongsList);
                    lvSongList.BringToFront();
                    lbTitle.Visible = true;
                    lbTitle.Text = "本地音乐";
                    Addmusic.Visible = true;
                    lbSongCount.Visible = true;
                    lbMusicName.Visible = false;
                    if (Is_login)
                        tsmiFavorite.Visible = true;
                    else
                        tsmiFavorite.Visible = false;
                    break;
                case 1:     //选中的是收藏音乐
                    lvSongList.Items.Clear();
                    AddSongsToListView(favoriteSongsList);
                    lvSongList.BringToFront();
                    lbTitle.Visible = true;
                    lbTitle.Text = "收藏音乐";
                    Addmusic.Visible = false;
                    lbSongCount.Visible = true;
                    lbMusicName.Visible = false;
                    tsmiFavorite.Visible = false;
                    break;
                case 2:  //选中的是用户
                    lbTitle.Visible = false;
                    Addmusic.Visible = false;
                    lbSongCount.Visible = false;
                    lbMusicName.Visible = false;
                    tsmiFavorite.Visible = false;
                    User.BringToFront();
                    break;
            }
            int songsCount = lvSongList.Items.Count;
            lbSongCount.Text = songsCount + "首音乐";
        }
        //专辑小图标点击事件
        private void picSmallAlbumImage_Click(object sender, EventArgs e)
        {
            pbAlbumImage.BringToFront();
            lbTitle.Visible = false;
            lbSongCount.Visible = false;
            Addmusic.Visible = false;
            lbMusicName.Visible = true;
            lbMusicName.Text = currPlaySong.OriginName;
        }
        #endregion

        #region 歌曲列表鼠标右击
        //让菜单选项出现在点击位置
        private void lvSongList_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ListViewItem lvi = lvSongList.GetItemAt(e.X, e.Y);
                if (lvi != null)
                {
                    currSelectedSong = new SongsInfo(lvi.SubItems[6].Text);
                    cmsSongListMenu.Show(Cursor.Position);
                    cmsSongListMenu.Visible = true;
                }
                else
                    cmsSongListMenu.Close();
            }
        }
        //菜单——收藏音乐
        private void tsmiFavorite_Click(object sender, EventArgs e)
        {
            foreach (SongsInfo song in favoriteSongsList)
            {
                if (currSelectedSong.FilePath == song.FilePath)
                    return;
            }
            favoriteSongsList.Add(new SongsInfo(currSelectedSong.FilePath));
            SaveSongsListHistory(favoriteSongsFilePath, favoriteSongsList);
        }
        //菜单——删除音乐
        private void tsmiRemoveSongFromList_Click(object sender, EventArgs e)
        {
            int removeIndex = lvSongList.SelectedItems[0].Index;
            if (lbMenu.SelectedIndex == 0)
            {
                localSongsList.RemoveAt(removeIndex);
                SaveSongsListHistory(localSongsFilePath, localSongsList);
                AddSongsToListView(localSongsList);
            }
            else if (lbMenu.SelectedIndex == 1)
            {
                favoriteSongsList.RemoveAt(removeIndex);
                SaveSongsListHistory(favoriteSongsFilePath, favoriteSongsList);
                AddSongsToListView(favoriteSongsList);
            }
        }
        //菜单——打开文件位置
        private void tsmiOpenFilePath_Click(object sender, EventArgs e)
        {
            //Explorer.exe 资源管理器
            System.Diagnostics.Process.Start(@"Explorer.exe", "/select,\"" + currSelectedSong.FilePath + "\"");
        }
        #endregion

        #region 用户登录
        //用户操作
        private void RegisterLog_Click(object sender, EventArgs e)
        {
            paLogin.BringToFront();
            paAfterLog.Visible = false;
        }
        private void LoginReg_Click(object sender, EventArgs e)
        {
            paRegister.BringToFront();
            paAfterLog.Visible = false;
        }
        private void LoginLog_Click(object sender, EventArgs e)
        {
            string username = LogUserName.Text;
            string passwd = LogPassWd.Text;
            string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\C#Projects\MusicPlayer\MusicPlayer\Database1.mdf;Integrated Security=True";
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select passwd from [dbo].[user] where username='" + username + "';";
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                string Passwd = (string)reader["passwd"];
                if (Passwd == passwd)
                {
                    paRegister.Visible = false;
                    paLogin.Visible = false;
                    Is_login = true;
                    paAfterLog.Visible = true;
                }
                else
                    MessageBox.Show("密码错误");
            }
            else
                MessageBox.Show("用户名错误!");
            con.Close();

        }
        private void RegisterReg_Click(object sender, EventArgs e)
        {
            string username = RegUsername.Text;
            string passwd = RegPasswd.Text;
            string passwd2 = RegPasswd2.Text;
            if (username == "" || passwd == "" || passwd2 == "")
            {
                MessageBox.Show("请检查填写内容！");
                return;
            }
            if(passwd != passwd2)
            {
                MessageBox.Show("两次密码不一样!");
                return;
            }
            string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\C#Projects\MusicPlayer\MusicPlayer\Database1.mdf;Integrated Security=True";
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from [dbo].[user] where username='" + username + "';";
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                MessageBox.Show("用户名已存在！");
                return;
            }
            reader.Close();
            SqlCommand cmd2 = con.CreateCommand();
            cmd2.CommandType = CommandType.Text;
            cmd2.CommandText = "insert into [dbo].[user] (username,passwd) values('" + username + "','" + passwd + "');";
            cmd2.ExecuteReader();
            con.Close();
            label3.Text = "注册成功,欢迎登录";
            paLogin.BringToFront();
        }
        #endregion

    }
}